package com.example.demo.interceptor;

import com.example.demo.context.BaseContext;
import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class AdminLoginCheckInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        String token=request.getHeader("token");

        try {
            log.info("jwt校验：{}",token);
            Claims claims= JwtUtils.parseJWT(token);
            Long id=Long.valueOf(claims.get("id").toString());
            log.info("当前管理员id：{}",id);
            BaseContext.setCurrentId(id);

            return true;
        } catch (NumberFormatException e) {
            response.setStatus(401);
            return false;
        }
    }
}
